package kuang.juc.pc;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//传统版本Synchronized
public class Juc_A {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decreasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decreasement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }

}

//使用while去判断，避免虚假唤醒
//如果用if只判断一次，多条线程去抢就会出现问题

/**
 * JUC版本的
 */
class Data2{
    private int number=0;
    //默认是非公平锁
    Lock lock=new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increasement() throws InterruptedException {
        //上锁
        lock.lock();
        //业务代码
        try {
            //判断等待
            while (number!=0){
                //juc版本的wait
                condition.await();
            }
            number++;
            //通知其它线程
            System.out.println(Thread.currentThread().getName()+"=>"+number);

            //juc版本的通知
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            lock.unlock();
        }
    }

    public void decreasement() throws InterruptedException {
        lock.lock();
        //业务代码
        try {
            //判断等待
            while (number==0){
                //juc版本的wait
                condition.await();
            }
            number--;
            //通知其它线程
            System.out.println(Thread.currentThread().getName()+"=>"+number);

            //juc版本的通知
            condition.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            lock.unlock();
        }
    }
}
